package svgedit.gui.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Logger;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import svgedit.gui.FileChooserDialog;
import svgedit.gui.Frame;
import svgedit.gui.SupportedFiles;

/**
 * Shows a file dialog for the user to select a new file to write the document
 * to, then saves it at that location.
 */
@SuppressWarnings("serial")
public class ExportDocumentAsAction
	extends AbstractAction
{

    private static final Logger logger = Logger.getLogger("svgedit");
    private Frame frame;

    /** Create this action for the given frame */
    public ExportDocumentAsAction(Frame frame)
    {
	super("Export As...");
	this.frame = frame;
    }

    public void actionPerformed(ActionEvent arg0)
    {

	File file = frame.getDocument().getFile();
	FileChooserDialog dialog;

	dialog =
		new FileChooserDialog(FileChooserDialog.FILE_EXPORT_DIALOG,
			frame.getPreferences().getDefaultPath());

	if (!(dialog.showSaveDialog(frame) == FileChooserDialog.APPROVE_OPTION))
	    return;

	file = dialog.getSelectedFile();

	SupportedFiles selectedFormat =
		(SupportedFiles) dialog.getFileFilter();
	if (selectedFormat != SupportedFiles.FileFilters.STAR_DOT_STAR)
	    file = SupportedFiles.ensureExtension(file, selectedFormat);

	if (file != null)
	    try
	    {
		if (file.exists() && !(file.canWrite()))
		    throw new IOException("File is read only");

		if (SupportedFiles.FileFilters.PNG_FILE_FILTER.validExt(file))
		{
		    logger.info(String.format("Exporting PNG to file %s",
			    file.getName()));
		    SupportedFiles.savePngImage(file);
		    return;
		}

		if (SupportedFiles.FileFilters.PDF_FILE_FILTER.validExt(file))
		{
		    logger.info(String.format("Exporting PDF to file %s",
			    file.getName()));
		    SupportedFiles.savePdfDocument(file);
		    return;
		}
		
		logger.info(String.format("Unsupported file format",
			    file.getName()));
		
		JOptionPane.showMessageDialog(frame.getRootPane(),
			"Unsupported File format", "Unable to save file",
			JOptionPane.ERROR_MESSAGE);
		
		
	    }
	    catch (IOException e)
	    {
		JOptionPane.showMessageDialog(frame.getRootPane(),
			e.getMessage(), "Unable to save file",
			JOptionPane.ERROR_MESSAGE);
	    }
    }
}
